import { useAuthStore } from "@/stores"
import { router } from "./index"
import { staticRotes } from './staticRotes'
import { adminDynamicRotes } from "./rotes/adminDynamicRotes"

// 弃用，放置在index后面

export const initDynamicRouter = async () => {
  const authStore = useAuthStore()

  try {
    // 1.请求用户信息，携带路由权限信息
    // await userStore.GetInfoAction()

    // 判断当前用户有没有菜单权限
    // if (!authStore.authRouterList.length) {
    //   ElNotification({
    //     title: '无权限访问',
    //     message: '当前账号无任何菜单权限，请联系系统管理员！',
    //     type: 'warning',
    //     duration: 3000,
    //   })
    //   RESEETSTORE()
    //   router.replace(LOGIN_URL)
    //   return Promise.reject('No permission')
    // }

    // 2.过滤路由
    const routerList = filterAsyncRoutes(
      adminDynamicRotes,
      authStore.authComponentList,
    )

    // 3.添加动态路由
    routerList.forEach((route) => {
      router.addRoute(route)
    })

    // 4.添加notFound路由
    // router.addRoute(notFoundRouter)

    // 5.处理subMenu数据,静态路由和动态路由拼接，过滤isHide=true的路由
    const menuList = getMenuList([
      ...staticRotes,
      ...routerList,
    ])
    console.log('menuList', menuList)
    authStore.setauthMenuList(menuList)
  } catch (error) {
    // 当按钮 || 菜单请求出错时，重定向到登陆页
    router.replace('/login')
    return Promise.reject(error)
  }
}

function filterAsyncRoutes(
  dynamicRoutes,
  authComponentList
) {
  return dynamicRoutes.filter((route) => {
    // 1.如果route的name在routeNames中没有, 直接过滤掉
    if (!authComponentList.includes(route.path)) return false

    // 2.如果当前route还有子路由(也就是有children), 需要对子路由也进行权限过滤
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRoutes(route.children, authComponentList)
    }
    return true
  })
}

function getMenuList(menuList) {
  const newMenuList = JSON.parse(JSON.stringify(menuList))

  return newMenuList.filter((item) => {
    item.children?.length && (item.children = getMenuList(item.children))
    return !item.meta?.isHide
  })
}

